package com.jiumi.api.controller;

import com.jiumi.api.base.BaseApiController;
import com.jiumi.api.entity.SysUserDo;
import com.jiumi.api.service.ILoginApiService;
import com.jiumi.api.util.WeiXinUtil;
import com.jiumi.api.vo.WxLoginVo;
import com.jiumi.baseconfig.domain.BaseUser;
import com.jiumi.baseconfig.service.IBaseUserService;
import com.jiumi.common.constant.Constants;
import com.jiumi.common.core.domain.AjaxResult;
import com.jiumi.common.core.domain.model.LoginBody;
import com.jiumi.common.core.redis.RedisCache;
import com.jiumi.common.utils.SecurityUtils;
import com.jiumi.common.utils.StringUtils;
import com.jiumi.config.WeiXinConfig;
import com.jiumi.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @author lun.zhang
 * @create 2022/10/18 10:58
 */
@RestController
@RequestMapping("/api")
public class LoginApiController extends BaseApiController {
    @Autowired
    private WeiXinConfig weiXinConfig;
    @Autowired
    private ILoginApiService loginApiService;


    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IBaseUserService userInfoService;

    @Autowired
    private ISysConfigService configService;



    @PostMapping("/noAuth/login")
    public AjaxResult login(@Validated @RequestBody WxLoginVo wxLoginVo) {
        String appId = weiXinConfig.getAppId();
        String appSecret = weiXinConfig.getAppSecret();
        Map<String, Object> mapResult = new HashMap<>();
        if ("debug".equalsIgnoreCase(wxLoginVo.getCode())) {
            mapResult.put("openid", wxLoginVo.getCode());
        } else {
            mapResult = WeiXinUtil.getWxUserOpenId(wxLoginVo.getCode(), appId, appSecret);
        }
        Object openid = mapResult.get("openid");
        String unionid = null;
        if (StringUtils.isNotNull(mapResult.get("unionid"))) {
            unionid = (String) mapResult.get("unionid");
        }
        if (StringUtils.isNull(openid)) {
            return AjaxResult.error("获取openid失败!");
        }
        mapResult.put("avatar", wxLoginVo.getAvatarUrl());
        mapResult.put("sex", wxLoginVo.getGender());
        mapResult.put("nickName", wxLoginVo.getNickName());
        mapResult.put("unionid", unionid);
        Map<String, Object> login = loginApiService.login(mapResult);
        return AjaxResult.success(login);
    }

    @PostMapping("/loginApp1")
    public AjaxResult loginApp1(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginApiService.loginApp(loginBody.getUsername(), loginBody.getPassword(), loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 找回密码
     */
    @PutMapping("/noAuth/fogetPwd")
    public AjaxResult fogetPwd(@RequestBody SysUserDo user) {
        String key = "phone_verify_code" + user.getUserName();
        String code = redisCache.getCacheObject(key) + "";
        if (!user.getCode().equals(code)) {
            return AjaxResult.error("验证码错误");
        }
        if (StringUtils.isEmpty(user.getAgainPassword())) {
            return AjaxResult.error("确认密码不能为空");
        }
        BaseUser currentUser = userInfoService.selectBaseUserByUserName(user.getUserName());
        String password = SecurityUtils.encryptPassword(user.getPassword());
        String againPwd = SecurityUtils.encryptPassword(user.getAgainPassword());
        if (!user.getPassword().equals(user.getAgainPassword())) {
            return AjaxResult.error("两次密码不一致");
        }

        return toAjax(userInfoService.resetUserPwdByPhone(user.getUserName(), againPwd));
    }

    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUserDo user) {
        if (StringUtils.isEmpty(user.getAgainPassword())) {
            return AjaxResult.error("确认密码不能为空");
        }
        BaseUser currentUser = userInfoService.selectBaseUserByUserId(getUserId());
        String againPwd = SecurityUtils.encryptPassword(user.getAgainPassword());
        if (!SecurityUtils.matchesPassword(user.getPassword(), currentUser.getPassword())) {
            return AjaxResult.error("当前密码错误，请联系管理员" );
        }

        return toAjax(userInfoService.resetUserPwdByPhone(currentUser.getUserName(), againPwd));
    }


}
